<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title th:text="${product.productId != null ? '编辑商品' : '添加商品'}">商品管理</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .preview-image {
            max-width: 200px;
            max-height: 200px;
            margin-top: 10px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .image-upload-area {
            border: 2px dashed #dee2e6;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            background-color: #f8f9fa;
            transition: all 0.3s ease;
        }
        .image-upload-area:hover {
            border-color: #0d6efd;
            background-color: #e7f3ff;
        }
        .image-upload-area.dragover {
            border-color: #0d6efd;
            background-color: #e7f3ff;
        }
        .category-group {
            margin-bottom: 1.5rem;
            padding: 1rem;
            border: 1px solid #dee2e6;
            border-radius: 0.25rem;
            display: none;
        }
        .category-group.active {
            display: block;
        }
        .category-parent {
            font-weight: bold;
            margin-bottom: 1rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid #e9ecef;
        }
        .category-children {
            padding-left: 1.5rem;
        }
        .category-group .form-check {
            margin-bottom: 0.5rem;
        }
        .form-check-input:checked + .form-check-label {
            color: #0d6efd;
            font-weight: bold;
        }
        .parent-categories {
            margin-bottom: 1.5rem;
        }
        .parent-category-btn {
            margin-right: 0.5rem;
            margin-bottom: 0.5rem;
        }
        .parent-category-btn.active {
            background-color: #0d6efd;
            color: white;
        }
        .no-categories-alert {
            text-align: center;
            padding: 2rem;
        }
        .current-image-container {
            position: relative;
            display: inline-block;
        }
        .image-info {
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.8rem;
            position: absolute;
            bottom: 4px;
            left: 4px;
        }
        .error-alert {
            margin-bottom: 1rem;
        }
    </style>
</head>
<body>
    <!-- 使用admin专用导航栏 -->
    <div th:replace="~{common/admin-navbar :: navbar}"></div>
    <div class="container mt-4">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h3 class="card-title mb-0" th:text="${product.productId != null ? '编辑商品' : '添加商品'}">商品管理</h3>
                    </div>
                    <div class="card-body">
                        <!-- 错误消息显示 -->
                        <div th:if="${error}" class="alert alert-danger alert-dismissible fade show error-alert" role="alert">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            <span th:text="${error}">错误信息</span>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                        
                        <!-- 检查是否有分类数据 -->
                        <div th:if="${parentCategories.empty}" class="alert alert-warning no-categories-alert">
                            <i class="fas fa-exclamation-triangle fa-3x mb-3"></i>
                            <h5>暂无分类数据</h5>
                            <p class="mb-3">在添加商品之前，请先创建商品分类。</p>
                            <a href="/admin/categories/add" class="btn btn-primary">
                                <i class="fas fa-plus-circle"></i> 立即添加分类
                            </a>
                        </div>

                        <form th:unless="${parentCategories.empty}" 
                              th:action="${product.productId != null ? '/admin/products/update' : '/admin/products/add'}" 
                              method="post" enctype="multipart/form-data" id="productForm">
                            
                            <!-- 编辑时需要隐藏的ID字段 -->
                            <input type="hidden" th:if="${product.productId != null}" 
                                   name="productId" th:value="${product.productId}">
                            
                            <div class="mb-3">
                                <label for="productName" class="form-label">商品名称</label>
                                <input type="text" class="form-control" id="productName" name="productName" 
                                       th:value="${product.productName}" required>
                            </div>

                            <div class="mb-3">
                                <label class="form-label d-block">商品分类</label>
                                <div class="alert alert-info">请先选择主分类，然后在相应的子分类中选择具体分类</div>

                                <!-- 父分类选择按钮组 -->
                                <div class="parent-categories">
                                    <button type="button" th:each="parent : ${parentCategories}"
                                            class="btn btn-outline-primary parent-category-btn"
                                            th:data-category-id="${parent.categoryId}"
                                            th:text="${parent.categoryName}">
                                        父分类名称
                                    </button>
                                </div>

                                <!-- 子分类选择区域 -->
                                <div class="category-groups">
                                    <div th:each="parent : ${parentCategories}"
                                         th:id="'category-group-' + ${parent.categoryId}"
                                         class="category-group">
                                        <div class="category-parent">
                                            <span th:text="${parent.categoryName}">父分类名称</span>
                                        </div>
                                        <div class="category-children">
                                            <div th:if="${subCategoriesMap.get(parent.categoryId).empty}" class="text-muted">
                                                该父分类下暂无子分类，请先<a th:href="@{/admin/categories/add}">添加子分类</a>
                                            </div>
                                            <div th:unless="${subCategoriesMap.get(parent.categoryId).empty}" 
                                                 th:each="child : ${subCategoriesMap.get(parent.categoryId)}" class="form-check">
                                                <input class="form-check-input" type="radio"
                                                       name="categoryId"
                                                       th:id="${'category-' + child.categoryId}"
                                                       th:value="${child.categoryId}" 
                                                       th:checked="${product.categoryId == child.categoryId}" required>
                                                <label class="form-check-label" 
                                                       th:for="${'category-' + child.categoryId}"
                                                       th:text="${child.categoryName}">
                                                    子分类名称
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label for="price" class="form-label">价格</label>
                                <div class="input-group">
                                    <span class="input-group-text">¥</span>
                                    <input type="number" class="form-control" id="price" name="price" 
                                           step="0.01" min="0" th:value="${product.price}" required>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label for="rest" class="form-label">库存数量</label>
                                <input type="number" class="form-control" id="rest" name="rest" 
                                       min="0" th:value="${product.rest}" required>
                            </div>

                            <div class="mb-3">
                                <label for="description" class="form-label">商品描述</label>
                                <textarea class="form-control" id="description" name="description" 
                                          rows="3" th:text="${product.description}" required></textarea>
                            </div>

                            <div class="mb-3">
                                <label for="productImage" class="form-label">商品图片</label>
                                
                                <!-- 当前图片显示（编辑模式） -->
                                <div th:if="${product.photo != null and !product.photo.isEmpty()}" class="mb-3">
                                    <small class="text-muted d-block mb-2">当前图片：</small>
                                    <div class="current-image-container">
                                        <img th:src="${product.photo}" class="preview-image" id="currentImage" alt="当前商品图片">
                                        <div class="image-info" id="currentImageInfo">当前图片</div>
                                    </div>
                                </div>
                                
                                <!-- 图片上传区域 -->
                                <div class="image-upload-area" id="uploadArea">
                                    <input type="file" class="form-control" id="productImage" name="productImage" 
                                           accept="image/jpeg,image/jpg,image/png,image/gif,image/bmp" 
                                           onchange="previewImage(this);"
                                           th:required="${product.productId == null}"
                                           style="display: none;">
                                    <label for="productImage" class="form-label mb-0" style="cursor: pointer;">
                                        <i class="fas fa-cloud-upload-alt fa-2x mb-2 text-primary"></i><br>
                                        <span class="text-primary">点击选择图片</span><br>
                                        <small class="text-muted">或拖拽图片到此区域</small><br>
                                        <small class="text-muted">支持 JPG、PNG、GIF、BMP 格式，最大 5MB</small>
                                    </label>
                                </div>
                                
                                <!-- 新图片预览 -->
                                <div id="newImagePreview" style="display: none;" class="mt-3">
                                    <small class="text-muted d-block mb-2">新图片预览：</small>
                                    <div class="current-image-container">
                                        <img id="preview" class="preview-image" alt="新图片预览">
                                        <div class="image-info" id="previewImageInfo">新图片</div>
                                    </div>
                                    <div class="mt-2">
                                        <button type="button" class="btn btn-sm btn-outline-secondary" onclick="clearPreview()">
                                            <i class="fas fa-times"></i> 取消选择
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <div class="d-grid gap-2">
                                <button type="submit" class="btn btn-primary" id="submitBtn"
                                        th:text="${product.productId != null ? '保存修改' : '添加商品'}">添加商品</button>
                                <a href="/admin/products" class="btn btn-secondary">取消</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/js/all.min.js"></script>
    <script>
        let selectedFile = null;
        
        function previewImage(input) {
            if (input.files && input.files[0]) {
                selectedFile = input.files[0];
                
                // 验证文件大小
                if (selectedFile.size > 5 * 1024 * 1024) {
                    alert('图片文件大小不能超过 5MB！');
                    clearPreview();
                    return;
                }
                
                // 验证文件类型
                const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp'];
                if (!allowedTypes.includes(selectedFile.type)) {
                    alert('请选择有效的图片格式（JPG、PNG、GIF、BMP）！');
                    clearPreview();
                    return;
                }
                
                var reader = new FileReader();
                reader.onload = function(e) {
                    $('#preview').attr('src', e.target.result);
                    $('#newImagePreview').show();
                    $('#currentImage').hide(); // 隐藏当前图片
                    
                    // 显示文件信息
                    const sizeText = formatFileSize(selectedFile.size);
                    $('#previewImageInfo').text(`新图片 (${sizeText})`);
                    
                    // 更新上传区域样式
                    $('#uploadArea').addClass('d-none');
                }
                reader.readAsDataURL(selectedFile);
            }
        }
        
        function clearPreview() {
            selectedFile = null;
            $('#productImage').val('');
            $('#newImagePreview').hide();
            $('#currentImage').show();
            $('#uploadArea').removeClass('d-none');
        }
        
        function formatFileSize(bytes) {
            if (bytes < 1024) return bytes + ' B';
            if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
            return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
        }

        $(document).ready(function() {
            // 获取当前商品的分类ID（如果是编辑模式）
            var currentCategoryId = /*[[${product.categoryId}]]*/ null;
            var selectedParentId = null;

            // 如果是编辑模式，需要找到当前分类所属的父分类
            if (currentCategoryId) {
                $('input[name="categoryId"]').each(function() {
                    if ($(this).val() === currentCategoryId) {
                        var parentGroupId = $(this).closest('.category-group').attr('id');
                        selectedParentId = parentGroupId.replace('category-group-', '');
                        return false; // 跳出循环
                    }
                });
            }

            // 父分类按钮点击事件
            $('.parent-category-btn').click(function() {
                var parentId = $(this).data('category-id');
                
                // 移除其他按钮的active类
                $('.parent-category-btn').removeClass('active');
                // 给当前按钮添加active类
                $(this).addClass('active');

                // 隐藏所有子分类组
                $('.category-group').removeClass('active');
                // 显示对应的子分类组
                $('#category-group-' + parentId).addClass('active');

                // 如果不是当前编辑的分类所在父分类，则取消选中
                if (!currentCategoryId || selectedParentId !== parentId) {
                    $('input[name="categoryId"]').prop('checked', false);
                }
            });

            // 初始化：如果是编辑模式，激活对应的父分类
            if (selectedParentId) {
                $('.parent-category-btn[data-category-id="' + selectedParentId + '"]').addClass('active');
                $('#category-group-' + selectedParentId).addClass('active');
            }

            // 拖拽上传功能
            const uploadArea = document.getElementById('uploadArea');
            const productImageInput = document.getElementById('productImage');
            
            uploadArea.addEventListener('dragover', function(e) {
                e.preventDefault();
                uploadArea.classList.add('dragover');
            });
            
            uploadArea.addEventListener('dragleave', function(e) {
                e.preventDefault();
                uploadArea.classList.remove('dragover');
            });
            
            uploadArea.addEventListener('drop', function(e) {
                e.preventDefault();
                uploadArea.classList.remove('dragover');
                
                const files = e.dataTransfer.files;
                if (files.length > 0) {
                    productImageInput.files = files;
                    previewImage(productImageInput);
                }
            });

            // 表单提交前验证
            $('#productForm').submit(function(e) {
                if (!$('input[name="categoryId"]:checked').length) {
                    e.preventDefault();
                    alert('请选择商品分类！');
                    return false;
                }
                
                // 检查是否需要图片（新增商品时）
                const isEditMode = /*[[${product.productId != null}]]*/ false;
                const hasCurrentImage = /*[[${product.photo != null and !product.photo.isEmpty()}]]*/ false;
                
                if (!isEditMode && !selectedFile) {
                    e.preventDefault();
                    alert('请选择商品图片！');
                    return false;
                }
                
                // 显示提交按钮加载状态
                $('#submitBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 处理中...');
                
                return true;
            });
        });
    </script>
</body>
</html>
